"use client";

import * as React from "react";
import { useForm } from "react-hook-form";
import { useParams } from "next/navigation";
import { useRouter } from "nextjs-toploader/app";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { BytemdEditor } from "@/components/Bytemd";
import {
  type CreateBlogDTO,
  verifyCreateBlog,
  createBlog,
  getBlogById,
  UpdateBlogDTO,
  verifyUpdateBlog,
  updateBlog,
} from "@/modules/blog";
import { useEffect, useMemo } from "react";
import { getTagListByType } from "@/modules/tag";
import { TagTypeEnum } from "@prisma/client";
import { Combobox } from "@/components/ui/combobox";

export default function Page() {
  const id = useParams().id;
  const isCreate = useMemo(() => id === "create", [id]);
  const router = useRouter();

  const getTagListByTypeController = getTagListByType(TagTypeEnum.BLOG);

  const tags = useMemo(() => {
    return getTagListByTypeController.data?.tags ?? [];
  }, [getTagListByTypeController]);

  const createBlogController = createBlog();

  const updateBlogController = updateBlog();

  const getBlogByIdController = getBlogById(id as string);

  const blog = useMemo(() => {
    return getBlogByIdController.data?.blog;
  }, [getBlogByIdController]);

  const form = useForm<UpdateBlogDTO | CreateBlogDTO>({
    resolver: zodResolver(isCreate ? verifyCreateBlog : verifyUpdateBlog),
    defaultValues: {
      id: blog?.id ?? "",
      title: blog?.title ?? "",
      description: blog?.description ?? "",
      content: blog?.content ?? "",
      published: blog?.published ?? true,
      cover: blog?.cover ?? "",
      tags: blog?.tags.map((el) => el.id) ?? [],
    },
  });

  useEffect(() => {
    form.setValue("title", blog?.title ?? "");
    form.setValue("id", blog?.id ?? "");
    form.setValue("description", blog?.description ?? "");
    form.setValue("content", blog?.content ?? "");
    form.setValue("published", blog?.published ?? true);
    form.setValue("cover", blog?.cover ?? "");
    form.setValue("tags", blog?.tags.map((el) => el.id) ?? []);
  }, [blog, form]);

  async function handleSubmit(values: CreateBlogDTO | UpdateBlogDTO) {
    if (!isCreate) {
      (values as UpdateBlogDTO).id = blog?.id!;
      await updateBlogController.runAsync(
        id as string,
        values as UpdateBlogDTO
      );
    } else {
      await createBlogController.runAsync(values as CreateBlogDTO);
    }

    router.push("/admin/blog");
  }

  return (
    <Form {...form}>
      <form autoComplete="off">
        <div className="grid gap-4 px-1 pb-24">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>标题</FormLabel>
                <FormControl>
                  <Input {...field} placeholder="请输入标题" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem>
                <FormLabel>描述</FormLabel>
                <FormControl>
                  <Textarea {...field} placeholder="请输入描述" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="cover"
            render={({ field }) => (
              <FormItem>
                <FormLabel>封面</FormLabel>
                <FormControl>
                  <Textarea
                    {...field}
                    value={field.value ?? ""}
                    placeholder="请输入封面链接"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="published"
            render={({ field }) => (
              <FormItem>
                <FormLabel>是否发布</FormLabel>
                <FormControl>
                  <div>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </div>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="tags"
            render={({ field }) => (
              <FormItem>
                <FormLabel>标签</FormLabel>
                <FormControl>
                  <div>
                    <Combobox
                      options={tags.map((el) => ({
                        label: el.name,
                        value: el.id,
                      }))}
                      multiple
                      clearable
                      selectPlaceholder="请选择标签"
                      value={field.value}
                      onValueChange={field.onChange}
                    />
                  </div>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="content"
            render={({ field }) => (
              <FormItem>
                <FormLabel>内容</FormLabel>
                <FormControl>
                  <div id="content-editor">
                    <BytemdEditor
                      body={field.value}
                      setContent={field.onChange}
                    />
                  </div>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button
            type="button"
            onClick={() => form.handleSubmit(handleSubmit)()}
            variant={"outline"}
            className="!w-full"
          >
            {isCreate ? "创建" : "更新"}
          </Button>
        </div>
      </form>
    </Form>
  );
}
